package com.powernode.model;

import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author 梁卓
 * @Version 1.0
 * @ClassName SecurityUser
 * @Description Security安全框架认识的对象
 * @Date 2024/07/20 23:51
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {

    // 商城后台管理系统用户的相关属性
    /**
     * 用户Id
     */
    private Long userId;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 状态  0：禁用   1：正常
     */
    private Integer status;
    /**
     * 用户所在的商城Id
     */
    private Long shopId;

    // 商城购物管理系统用户的相关属性


    /**
     * 登录用户类型
     */
    private String loginType;

    /**
     * 用户权限集合
     */
    private Set<String> perms;

    /**
     * getter 方法
     */
    public Set<String> getPerms() {
        HashSet<String> finalPermsSet = new HashSet<>(this.perms.size());
        perms.forEach(perm -> {
            // 判断权限记录是否包含","号
            if (perm.contains(",")) {
                // 根据","号分隔, 放在新的集合中
                finalPermsSet.addAll(Arrays.asList(perm.split(",")));
            } else {
                finalPermsSet.add(perm);
            }
        });
        this.perms = finalPermsSet;
        return finalPermsSet;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return getPerms().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.loginType + this.userId;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }
}
